package com.maweirdos.gulimall.order.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Maweirdos
 * @Date: 2024/5/13 21:09
 */
@Configuration
public class GuliFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            // 1. 使用RequestContextHolder拿到刚进来的请求
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = attributes.getRequest();
            if (request != null) {
                // 2.同步请求头数据，Cookie
                String cookie = request.getHeader("Cookie");
                // 3.给新请求同步请求头数据
                requestTemplate.header("Cookie", cookie);
            }
        };
    }
}
